﻿Imports System.Windows.Controls.Primitives

Partial Public Class ImageThumbnailList

    Public Sub New()
        InitializeComponent()
        MyInitialize()
    End Sub

    Private Sub MyInitialize()
        'lvw.SelectionMode = SelectionMode.Single
        If System.ComponentModel.DesignerProperties.GetIsInDesignMode(Me) Then Return

        AddHandler g_album_mgr.AlbumLoaded, AddressOf OnAlbumLoaded
        AddHandler g_connection.ConnectionChanged, AddressOf OnConnectionChanged
        AddHandler g_currentphoto.Changed, AddressOf OnPhotoChanged
    End Sub

    Private Delegate Sub DlgOnConnectionChanged()
    Private Sub OnConnectionChanged()
        If Not Dispatcher.CheckAccess() Then
            Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Normal, New DlgOnConnectionChanged(AddressOf OnConnectionChanged))
        Else
            lvw.Items.Clear()
        End If
    End Sub

    Private Const BORDER_SIZE As Integer = 10
    Private Const THUMBNAIL_SIZE As Integer = 96
    Private Const SCROLLBAR_SIZE As Integer = 20

    Private m_override_measure_size As Size

    Private Sub LoadThumbnails()

        m_deferred = False
        'Return

        ReportingUtils.StartTimer()

        If g_album_mgr Is Nothing Then Return
        If g_album_mgr.Photos Is Nothing Then Return

        lvw.Items.Clear()

        SetTemplate(GetNCols(m_override_measure_size.Width))
        'lvw.ItemsPanel = Me.Resources.Item("Col3")

        For i As Integer = 1 To 1 '10
            For Each row As DataRow In g_album_mgr.Photos.Rows
                Dim filename As String = CType(row.Item("FileName"), String)

                Dim b() As Byte = CType(row.Item("Thumbnail"), Byte())
                Dim bi As BitmapImage = ConvertBytesToImage(b)

                Dim img As New Image
                img.Width = THUMBNAIL_SIZE
                img.Height = THUMBNAIL_SIZE
                img.Stretch = Stretch.Uniform
                img.StretchDirection = StretchDirection.Both
                img.HorizontalAlignment = Windows.HorizontalAlignment.Center
                img.VerticalAlignment = Windows.VerticalAlignment.Center
                img.Source = bi

                Dim pnl As New StackPanel
                pnl.Children.Add(img)

                Dim title As New Label
                title.MaxWidth = THUMBNAIL_SIZE
                title.HorizontalContentAlignment = Windows.HorizontalAlignment.Center
                Try
                    title.Content = CType(row.Item("ImageName"), String)
                    title.Foreground = Brushes.Gray
                Catch
                    title.Content = "NULL"
                    title.Foreground = Brushes.LightGray
                    title.FontWeight = FontWeights.Bold
                    title.FontStyle = FontStyles.Oblique
                End Try
                pnl.Children.Add(title)

                Dim title2 As New Label
                title2.MaxWidth = THUMBNAIL_SIZE
                title2.HorizontalContentAlignment = Windows.HorizontalAlignment.Center
                Try
                    title2.Content = CType(row.Item("PixelWidth"), String) & " x " & CType(row.Item("PixelHeight"), String)
                    title2.Foreground = Brushes.Gray
                    pnl.Children.Add(title2)
                Catch : End Try


                Dim bord As New Border
                bord.Margin = New Thickness(BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE)
                'bord.BorderThickness = New Thickness(1)
                'bord.BorderBrush = Brushes.BlueViolet
                bord.Child = pnl
                bord.ToolTip = title.Content

                Dim lvi As New ListViewItem
                lvi.Content = bord
                lvi.Tag = row
                lvw.Items.Add(lvi)
            Next
        Next

        ReportingUtils.ShowTimer("update thumbnails")

    End Sub


    Private Delegate Sub DlgOnPhotoChanged()
    Private Sub OnPhotoChanged()
        If Not Dispatcher.CheckAccess() Then
            Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Normal, New DlgOnPhotoChanged(AddressOf OnPhotoChanged))
        Else
            If g_currentphoto Is Nothing Then Return
            Dim row As DataRow = g_currentphoto.Row
            If row Is Nothing Then Return
            Dim rowguid As Guid = CType(row.Item("RowGuid"), Guid)
            If rowguid = Guid.Empty Then Return

            lvw.SelectedItem = Nothing
            For Each lvi As ListViewItem In lvw.Items
                row = CType(lvi.Tag, DataRow)
                If CType(row.Item("RowGuid"), Guid) = rowguid Then
                    lvw.SelectedItem = lvi
                    'CONVERT:lvw.SelectedIndices.Add(lvw.Items.IndexOf(lvi))
                End If
            Next
        End If
    End Sub

    Private m_deferred As Boolean

    Private Delegate Sub DlgOnAlbumLoaded()
    Private Sub OnAlbumLoaded()
        If Not Dispatcher.CheckAccess() Then
            Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Normal, New DlgOnAlbumLoaded(AddressOf OnAlbumLoaded))
        Else
            LoadThumbnails()
        End If
    End Sub

    Private Sub lvw_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvw.MouseDoubleClick
        If lvw.SelectedItem Is Nothing Then Return
        Dim lvi As ListViewItem = lvw.SelectedItem
        Dim row As DataRow = CType(lvi.Tag, DataRow)
        If row Is Nothing Then Return
        ImageViewerForm.ShowFullImage(row)
    End Sub

    Protected Overrides Function MeasureOverride(ByVal constraint As System.Windows.Size) As System.Windows.Size
        Trace.WriteLine("MeasureOverride in : " & constraint.ToString)
        Dim ncols As Integer = GetNCols(constraint)
        Dim width As Integer = GetWidth(ncols)
        If Not Double.IsInfinity(constraint.Width) Then width = constraint.Width
        If Double.IsInfinity(constraint.Height) Then
            m_override_measure_size = New Size(GetWidth(ncols), GetHeight(ncols))
        Else
            m_override_measure_size = New Size(GetWidth(ncols), constraint.Height)
        End If
        Trace.WriteLine("MeasureOverride out: " & m_override_measure_size.ToString)
        Return m_override_measure_size
    End Function

    'Protected Overrides Function ArrangeOverride(ByVal arrangeBounds As System.Windows.Size) As System.Windows.Size
    '    Trace.WriteLine("ArrangeOverride in : " & arrangeBounds.ToString)
    '    Dim ncols As Integer = GetNCols(arrangeBounds)
    '    LoadThumbnails()
    '    Dim s As New Size(GetWidth(ncols), GetHeight(ncols))
    '    Trace.WriteLine("ArrangeOverride out: " & s.ToString)
    '    Return s
    'End Function

    Private Function GetNCols(ByVal size As System.Windows.Size) As Integer
        Return GetNCols(size.Width)
    End Function

    Private Sub SetTemplate(ByVal ncols As Integer)
        Dim templatename As String = "Col" & ncols
        Trace.WriteLine("SetTemplate: " & templatename)
        lvw.ItemsPanel = Me.Resources.Item(templatename)
    End Sub

    Private Function GetNCols(ByVal width As Double) As Integer
        If Double.IsNaN(width) OrElse Double.IsPositiveInfinity(width) Then Return 1
        Dim tilewidth As Integer = THUMBNAIL_SIZE + 2 * BORDER_SIZE
        Dim ncols As Integer = Math.Floor((width - SCROLLBAR_SIZE) / tilewidth)
        If ncols < 1 Then ncols = 1
        If ncols > 20 Then ncols = 20
        Return ncols
    End Function

    Private Function GetWidth(ByVal ncols As Integer) As Double
        Dim tilewidth As Integer = THUMBNAIL_SIZE + 2 * BORDER_SIZE
        Return ncols * tilewidth
    End Function


    Private Function GetHeight(ByVal ncols As Integer) As Double
        Dim nphotos As Integer = 0
        Try
            nphotos = g_album_mgr.Photos.Rows.Count
        Catch : End Try
        Dim nrows As Integer = Math.Max(1, nphotos / ncols)
        Dim tileheight As Integer = THUMBNAIL_SIZE + 2 * BORDER_SIZE
        Return nrows * tileheight
    End Function

    Private Sub ImageThumbnailList_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles Me.SizeChanged
        e.Handled = True
        If Not e.WidthChanged Then Return

        Dim tilewidth As Integer = THUMBNAIL_SIZE + 2 * BORDER_SIZE
        Dim nwide As Integer = e.NewSize.Width / tilewidth
        If nwide < 1 Then nwide = 1
        If nwide > 20 Then nwide = 20

        Dim templatename As String = "Col" & nwide
        lvw.ItemsPanel = Me.Resources.Item(templatename)
    End Sub

    Private Sub lvw_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvw.SelectionChanged
        Dim lvi As ListViewItem = lvw.SelectedItem
        If lvi Is Nothing Then Return
        Dim row As DataRow = CType(lvi.Tag, DataRow)
        g_currentphoto.Row = row
    End Sub
End Class
